package com.tengfei.ui_widget;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class EditTextActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edittext);
        getSupportActionBar().setTitle("EditText");
        EditText etDemo = findViewById(R.id.etDemo);
        etDemo.setTextColor(Color.BLUE);
        etDemo.setText("");
        etDemo.setHint("输入名字");
        etDemo.setHintTextColor(Color.rgb(0, 200, 200));
        etDemo.setBackgroundColor(Color.parseColor("#ff00ab"));
        etDemo.setEms(12);  //设置可视宽度
        etDemo.setFilters(new InputFilter[]{
                new InputFilter.LengthFilter(10)
        });

        EditText etPasswordDemo = findViewById(R.id.etPassword);
        Switch swPassword = findViewById(R.id.swPassword);
        swPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    etPasswordDemo.setInputType(InputType.TYPE_CLASS_TEXT);
                    buttonView.setText("隐藏密码");
                }else {
                    etPasswordDemo.setInputType(InputType.TYPE_CLASS_TEXT
                            | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    buttonView.setText("显示密码");
                }
            }
        });

        TextView tvShow = findViewById(R.id.tv_show);
        etDemo.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                tvShow.setText(etDemo.getText());
                return false;
            }
        });

        etDemo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tvShow.setText(s);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }
}